package com.qls.core.utils;

import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author doyoung
 */
public class MapUtil {

    /**
     * 将map 拆分成多个map
     *
     * @param <k>      map 的 key类 型
     * @param <v>      map 的value 类型
     * @param chunkMap 被拆的 map
     * @param chunkNum 每段的大小
     * @return List
     */
    public static <k, v> List<Map<k, v>> mapChunk(Map<k, v> chunkMap, int chunkNum) {
        if (chunkMap == null || chunkNum <= 0) {
            List<Map<k, v>> list = new ArrayList<>();
            list.add((Map<k, v>) chunkMap);
            return list;
        }
        Set<k> keySet = chunkMap.keySet();
        Iterator<k> iterator = keySet.iterator();
        int i = 1;
        List<Map<k, v>> total = new ArrayList<>();
        Map<k, v> tem = new HashMap<>();
        while (iterator.hasNext()) {
            k next = iterator.next();
            tem.put(next, chunkMap.get(next));
            if (i == chunkNum) {
                total.add(tem);
                tem = new HashMap<>();
                i = 0;
            }
            i++;
        }
        if (!CollectionUtils.isEmpty(tem)) {
            total.add(tem);
        }
        return total;
    }

}
